package com.n.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.n.application.SystemCache;
import com.n.common.BaseAction;
import com.n.dao.CustomerDao;
import com.n.model.Customer;

@Controller
@RequestMapping("/customer")
public class CustomerAction extends BaseAction {
	
	static final String PRE_PATH = "/admin/customer/";
	
	@Autowired
	CustomerDao customerDao;
	
	
	@RequestMapping(value="save.do")
	@ResponseBody
	public String save(HttpServletRequest request){
		String sid = request.getParameter("id");
		Customer c = new Customer();
		c.setName(request.getParameter("name"));
		c.setArea(Integer.parseInt(request.getParameter("area")));
		c.setCode(request.getParameter("code"));;
		c.setLevel(Integer.parseInt(request.getParameter("level")));
		if(!StringUtils.isEmpty(sid)){
			c.setId(Integer.parseInt(sid));
		}
		customerDao.merge(c);
		
		SystemCache.buildCustomer(customerDao);
		
		return SUCCESS;
	}
	
	@RequestMapping(value="list.do")
	public String list(HttpServletRequest request, ModelMap model){
		List<Customer> data = (List<Customer>)customerDao.loadAll(Customer.class);
		model.put("data", processData(data));
		model.put("customer_area_data", SystemCache.CUSTOMER_AREA_LIST);
		return PRE_PATH + "index";
	}
	
	@RequestMapping(value="load.do")
	@ResponseBody
	public String load(HttpServletRequest request){
		String sid = request.getParameter("id");
		if(StringUtils.isEmpty(sid)){
			return ERROR;
		}
		int id = Integer.parseInt(sid);
		Customer c = customerDao.load(Customer.class, id);
		JSONObject json = JSONObject.fromObject(c);
		json.put("success", SUCCESS);
		System.out.println(json);
		return json.toString();
	}
	
	@RequestMapping(value="del.do")
	@ResponseBody
	public String del(HttpServletRequest request){
		String sid = request.getParameter("id");
		if(StringUtils.isEmpty(sid)){
			return ERROR;
		}
		int id = Integer.parseInt(sid);
		customerDao.del(id);
		
		SystemCache.buildCustomer(customerDao);
		
		return SUCCESS;
	}
	
	private List<Customer> processData(List<Customer> data){
		for (Customer c : data) {
			c.setAreaName(SystemCache.CUSTOMER_AREA_MAP.get(c.getArea()));
		}
		return data;
	}

}
